package org.apache.servicecomb.samples.practise.houserush.realestate.service;

import org.apache.servicecomb.samples.practise.houserush.realestate.dao.BuildingDao;
import org.apache.servicecomb.samples.practise.houserush.realestate.dao.RealestateDao;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.Building;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.Realestate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BuildingServiceImpl implements BuildingService {

    @Autowired
    private BuildingDao buildingDao;
    @Autowired
    private RealestateDao realestateDao;

    @Override
    public Building createBuilding(Integer realestateId, Building building) {
        Realestate realestate = realestateDao.findOne(realestateId);
        if (null == realestate) {
            throw new DataRetrievalFailureException("对应楼盘不存在，无法添加楼栋信息");
        } else {
            building.setRealestate(realestate);
            return buildingDao.save(building);

        }
    }

    @Override
    public Building findBuilding(Integer id) {
        return buildingDao.findOne(id);
    }

    @Override
    @Transactional
    public Building updateBuilding(Building building) {
        int id = building.getId();
        if(buildingDao.exists(id)) {
            return buildingDao.save(building);
        } else {
            throw new DataRetrievalFailureException("不存在该楼栋，无法执行更新操作");
        }
    }

    @Override
    @Transactional
    public void removeBuilding(Integer id) {
        buildingDao.delete(id);
    }

    @Override
    public List<Building> indexBuildings(Integer realestateId) {
        Realestate realestate = realestateDao.findOne(realestateId);

        return realestate.getBuildings();
    }
}
